﻿using CodeCreator;
using CodeCreator.CoreObj;
using CodeCreator.CoreObj.DbManager;
using CodeCreator.Template;
using CodeTemplate.CodeEdit;
using CodeTemplate.Template;
using Common;
using iBing.Common.DbHelper;
using iBing.Common.DbHelper.CoreObj;
using iBing.PluginFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CodeTemplate
{
    public partial class CodeForm : DockBar
    {
        private string pluginKey;
        private IApplication application;
        private IDbHelper dbHelper = null;
        private Obj obj = null;
        private string temDirPath;
        private string temFilePath;

        #region 初始化
        public CodeForm(IApplication application, IDbHelper dbHelper, string schemaName, string tableName)
        {
            InitializeComponent();
            this.application = application;
            this.dbHelper = dbHelper;
            this.txtClassName.Text = Tools.DbFile2JavaFieldWidtFirstUpper(tableName);
            pluginKey = "TABLE_" + schemaName + "_" + tableName;
            this.temDirPath = System.Windows.Forms.Application.StartupPath + "\\Objs\\";
            if (!Directory.Exists(temDirPath))
            {
                Directory.CreateDirectory(temDirPath);
            }
            this.temFilePath = this.temDirPath + pluginKey + ".tmp";
            if (File.Exists(this.temFilePath))
            {
                if (MessageBox.Show(this, "是否在上次编辑基础上修改？", "询问", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    this.obj = ToolsSerialize.XmlDeserialize<Obj>(this.temFilePath);
                }
                else
                {
                    this.obj = GetObjForTable(schemaName, tableName);
                }
            }
            else
            {
                this.obj = GetObjForTable(schemaName, tableName);
            }
        }

        public CodeForm(IApplication application, IDbHelper dbHelper, string sql)
        {
            InitializeComponent();
            this.application = application;
            this.dbHelper = dbHelper;
            pluginKey = "SQL";
            this.temDirPath = System.Windows.Forms.Application.StartupPath + "\\Objs\\";
            if (!Directory.Exists(temDirPath))
            {
                Directory.CreateDirectory(temDirPath);
            }
            this.temFilePath = this.temDirPath + pluginKey + ".tmp";
            if (File.Exists(this.temFilePath))
            {
                if (MessageBox.Show(this, "是否在上次编辑基础上修改？", "询问", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    this.obj = ToolsSerialize.XmlDeserialize<Obj>(this.temFilePath);
                }
                else
                {
                    this.obj = GetObjForSql(sql);
                }
            }
            else
            {
                this.obj = GetObjForSql(sql);
            }
        }
        #endregion

        #region 编辑操作
        /// <summary>
        /// 编辑查询区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panQuery_DoubleClick(object sender, EventArgs e)
        {
            using (FrmEditForQuery frm = new FrmEditForQuery(this.obj.Conditions))
            {
                if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    //查询参数赋值
                    this.obj.Conditions = frm.Conditions;
                }
            }
        }
        /// <summary>
        /// 编辑表格呈现区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panForTable_DoubleClick(object sender, EventArgs e)
        {
            using (FrmEditForTable frm = new FrmEditForTable(this.obj.JsFields))
            {
                if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    //查询结果
                    this.obj.JsFields = frm.JsFields;
                }
            }
        }

        /// <summary>
        /// 生成代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateCode_Click(object sender, EventArgs e)
        {
            //判断命名空间
            if (this.txtPluginName.Text.Trim() == "")
            {
                using (FrmMessage fr = new FrmMessage("请填写完整包名！"))
                {
                    fr.ShowDialog(this);
                    this.txtPluginName.Focus();
                }
                return;
            }
            //判断类名
            if (this.txtClassName.Text.Trim() == "")
            {
                using (FrmMessage fr = new FrmMessage("请填写类名！"))
                {
                    fr.ShowDialog(this);
                    this.txtClassName.Focus();
                }
                return;
            }

            if (this.obj == null)
            {
                this.obj = GetObjForSql("");
            }
            //补充相关信息
            this.obj.JavaClassName = this.txtClassName.Text.Trim();
            this.obj.JavaObjName = Tools.DbFile2JavaFieldWidtFirstLower(obj.JavaClassName);
            this.obj.JsClassName = Tools.DbFile2JavaFieldWidtFirstUpper(obj.JavaClassName).ToLower();
            this.obj.JsObjName = Tools.DbFile2JavaFieldWidtFirstLower(obj.JavaClassName);
            this.obj.PackageName = this.txtPackageName.Text + "." + this.txtPluginName.Text;
            this.obj.PluginName = this.txtPluginName.Text;

            //将Obj序列化生成文件并保存
            ToolsSerialize.XmlSerialize<Obj>(this.obj, this.temFilePath);

            //导出
            using (FrmCreateTemplate frm = new FrmCreateTemplate(this.obj))
            {
                if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    //完成查询
                }
            }
        }
        #endregion

        #region 初始化对象
        private Obj GetObjForSql(string sql)
        {
            string strMapPath = System.Windows.Forms.Application.StartupPath + "\\TypeMap.xml";
            List<TypeMap> typeMap = Tools.getTypeMap(strMapPath);

            Obj obj = new Obj();
            //加载字段
            string strCheckSql = "select * from (" + sql + ") where 1=2";
            DataSet ds = this.dbHelper.Query(strCheckSql);
            List<DbField> dbFields = new List<DbField>();
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    DbField of = new DbField();
                    of.FieldLength = "1024";
                    of.FieldName = dc.ColumnName;
                    of.IsPk = false;
                    TypeMap tm = Tools.GetTypeMapByCSharp(typeMap, dc.DataType.Name);
                    if (tm != null)
                    {
                        of.FieldType = tm.DbType;
                    }
                    else
                    {
                        of.FieldType = dc.DataType.Name;
                    }
                    dbFields.Add(of);
                }
            }
            obj.DbPkFieldName = "NONE";
            obj.JavaPkName = "NONE";
            obj.DbSchemaName = "NONE";
            obj.DbTableName = "NONE";
            obj.DbSequenceName = "NONE";
            obj.DbFields = dbFields;


            //构建Java类属性
            obj.JavaFields = ToolForGetJavaFields.getJavaFields(obj.DbFields, typeMap);


            //构建表的SQL
            ToolForGetSqls toolForGetSql = new ToolForGetSqls(sql,obj.DbFields);
            obj.Sqls = toolForGetSql.GetDataForSql();

            //构建Js类属性
            obj.JsPkFieldName = Tools.DbFile2JavaFieldWidtFirstLower(obj.DbPkFieldName);
            obj.JsFields = ToolForGetJsFields.getJsFields(obj.DbFields, typeMap);

            //构建查询条件
            obj.Conditions = ToolForGetConditions.getObjForConditions(dbFields);
            return obj;
        }

        private Obj GetObjForTable(string schemaName, string tableName)
        {
            string strMapPath = System.Windows.Forms.Application.StartupPath + "\\TypeMap.xml";
            List<TypeMap> typeMap = Tools.getTypeMap(strMapPath);

            Obj obj = new Obj();
            //加载字段
            List<DbField> dbFields = this.dbHelper.GetColumnsByTable(schemaName, tableName);
            obj.DbPkFieldName = ToolForGetDbPk.GetPkFieldName(dbFields);
            obj.DbSchemaName = schemaName;
            obj.DbTableName = tableName;
            obj.DbSequenceName = "SEQ_" + tableName;
            obj.DbFields = dbFields;

            //如果没有主键手工指定
            if (obj.DbPkFieldName == "")
            {
                FrmGetPk frmGetPk = new FrmGetPk(obj.DbTableName, dbFields);
                if (frmGetPk.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    obj.DbPkFieldName = frmGetPk.PkFieldName;
                }
            }

            //构建Java类属性
            obj.JavaClassName = Tools.DbFile2JavaFieldWidtFirstUpper(obj.DbTableName);
            obj.JavaObjName = Tools.DbFile2JavaFieldWidtFirstLower(obj.DbTableName);
            obj.JavaPkName = Tools.DbFile2JavaFieldWidtFirstLower(obj.DbPkFieldName);
            obj.JavaFields = ToolForGetJavaFields.getJavaFields(obj.DbFields, typeMap);


            //构建表的SQL
            ToolForGetSqls toolForGetSql = new ToolForGetSqls(obj.DbSchemaName, obj.DbTableName, obj.JavaFields);
            obj.Sqls = toolForGetSql.GetDataForTable();

            //构建Js类属性
            obj.JsClassName = Tools.DbFile2JavaFieldWidtFirstUpper(obj.DbTableName).ToLower();
            obj.JsObjName = Tools.DbFile2JavaFieldWidtFirstLower(obj.DbTableName);
            obj.JsPkFieldName = Tools.DbFile2JavaFieldWidtFirstLower(obj.DbPkFieldName);
            obj.JsFields = ToolForGetJsFields.getJsFields(obj.DbFields, typeMap);

            //构建查询条件
            obj.Conditions = ToolForGetConditions.getObjForConditions(dbFields);
            return obj;
        }
        #endregion

        private void CodeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.application.DockBarService.RemoveDockBar(pluginKey, pluginKey);
        }


    }
}
